/**
 * Script of the page newest videos
 */
var PageVideoNewest = new (function() {
	var $this = this;
	var videosDisplayed = [];
	var loadingFirst = false;
	var loadingNext = false;
	var haveMore = true;
	var haveError = false;
	var ajax;
	
	/**
	 * Init
	 * Load status in localStorage
	 */
	this.init = function(e, data) {

		var prevpage = data.prevPage;
		loadVideoNewest();
		if (!videosDisplayed.length && !$("#video-newest-offset").val()) {
			$this.searchVideos();
		}
	}
	
	
	/**
	 * Search videos
	 * Offset broken in original website
	 */
	this.searchVideos = function() {
		var dataAjax = {
			login: MikuClip.options.login, 
			password: MikuClip.options.password,
		};
		/*
		if ($("#video-newest-offset").val()) {
			dataAjax.offset = $("#video-newest-offset").val();
		}
		*/
		
		if (ajax) {
			ajax.abort();
			ajax = null;
		}		
		
		if (!dataAjax.offset) {
			loadingFirst = true;
			clearListView();
		}
		else {
			loadingNext = true;
		}
		haveMore = true;
		haveError = false;
		updateListView();
		
		ajax = $.ajax({
			url: MikuClip.URL.WEBSERVICE_VIDEOS_NEWEST,
			data: dataAjax,
			type: 'POST',
			success: function(data) {
				try {
					
					var o = JSON.parse(data);
					saveVideoNewest();
					if (o.error_type && o.error_type == "connection") {
						DialogConnectMikubook.setError(o.error);
						DialogConnectMikubook.show();
					}
					else {
						var videos = o.videos;
						$("#page-video-newest #last-update").html(o.lastupdate);
						
						for (var i = 0; i < videos.length; i++) {
							addToListView(videos[i]);
							videosDisplayed.push(videos[i]);
						}
						loadingNext = false;
						loadingFirst = false;
						if (videos.length == 0) {
							haveMore = false;
						}
						
						updateListView();
						$("#video-newest-offset").val($("#page-video-newest #listview .video-item").length);
						
						saveVideoNewest();
						ajax = null;
					}
				}
				catch (e) {
					onError({statusText: 'parsing_error'});
				}
			},
			error: onError
		});
	}
	
	/**
	 * Error occured (403, 404, ...) or in parsing
	 */
	function onError(e) {
		loadingNext = false;
		loadingFirst = false;
		if (e.statusText != "abort") {
			haveError = true;
		}
		ajax = null;
		updateListView();
	}
	
	/**
	 * Click on "more elements" (broken)
	 */
	function onMoreVideo() {
		$this.searchVideos();
	}
	
	/**
	 * Click on refresh button
	 */
	function onRefresh() {
		$("#video-newest-offset").val('');
		videosDisplayed = [];
		$this.searchVideos();		
	}
		
	
	/**
	 * Save the current status of the page (video loading, videos displayed, offset)
	 */
	function saveVideoNewest() {
		window.localStorage['page_videoNewest'] = JSON.stringify({
			'offset': $("#video-newest-offset").val(),
			'videos': videosDisplayed,
			'loadingNext': loadingNext,
			'loadingFirst': loadingFirst,
			'haveMore': haveMore,
			'lastUpdate': $("#page-video-newest #last-update").html()
		});
	}
	
	/**
	 * Load the saved status of the page
	 */
	function loadVideoNewest() {
		if (window.localStorage['page_videoNewest']) {
			var o = JSON.parse(window.localStorage['page_videoNewest']);
			$("#video-newest-offset").val(o.offset);
			$("#page-video-newest #last-update").html(o.lastUpdate);
			
			videosDisplayed = [];
			
			if (!o.loadingFirst) {
				clearListView();
				for (var i = 0; i < o.videos.length; i++) {
					addToListView(o.videos[i]);
					videosDisplayed.push(o.videos[i]);
				}
			}
			
			updateListView();
			
			if (o.loadingNext || o.loadingFirst) {
				$this.searchVideos();
			}
			
		}
	}
	
	/**
	 * Update the main listview (more element, loading, error, no videos)
	 */
	function updateListView() {
		if (loadingFirst) {
			$("#page-video-newest #listview-loader-top").css("display", "block");
		}
		else {
			$("#page-video-newest #listview-loader-top").css("display", "none");
		}
		
		if (loadingNext) {
			$("#page-video-newest #listview-loader-bottom").css("display", "block");
		}
		else {
			$("#page-video-newest #listview-loader-bottom").css("display", "none");
		}
		
		if (videosDisplayed.length && haveMore && !loadingFirst && !loadingNext) {
			$("#page-video-newest #listview-item-more").css("display", "block");
		}
		else {
			$("#page-video-newest #listview-item-more").css("display", "none");
		}
	
	
		if (!haveError && !videosDisplayed.length && !loadingFirst && !loadingNext) {
			$("#page-video-newest #listview-item-notfound").css("display", "block");
		}
		else {
			$("#page-video-newest #listview-item-notfound").css("display", "none");
		}
		
		if (haveError) {
			$("#page-video-newest #listview-item-error").css("display", "block");
		}
		else {
			$("#page-video-newest #listview-item-error").css("display", "none");
		}
		
		refreshListView();
	}
	
	/**
	 * Clear the main list view
	 */
	function clearListView() {
		$("#page-video-newest #listview .video-item").remove();
		refreshListView();
	}
	
	/**
	 * Add an video to listview
	 */
	function addToListView(videodata) {
		var video = new VideoItem(videodata);
		$("#page-video-newest #listview-loader-bottom").before(video.dom);
		refreshListView();
	}
	
	/**
	 * Refresh the JQuery Mobile Widget, if loaded
	 */
	function refreshListView() {
		try {
			$("#page-video-newest #listview").listview('refresh');
		} catch(e) {
		}
	}	

	
	$("body").on("pagebeforeshow", "#page-video-newest", this.init);
	$("#page-video-newest #listview-item-more").on("click", onMoreVideo);
	$("#page-video-newest").on("click", "#btn-refresh", onRefresh);
});